package com.zw.weiyi.util;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.zw.weiyi.enety.SMS;
import com.zw.weiyi.phonesms.R;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.ContactsContract;

public class SMSUtil {
	
	public static final String CONTENT_URI_SMS = "content://sms"; // 短信
	public static final String CONTENT_URI_SMS_INBOX = "content://sms/inbox";// 收件箱
	public static final String CONTENT_URI_SMS_SENT = "content://sms/sent"; // 发送
	public static final String CONTENT_URI_SMS_CONVERSATIONS = "content://sms/conversations";

	public SMSUtil(Context mContext) {
		this.mContext = mContext;
	}

	public static String[] SMS_COLUMNS = new String[] { "_id", // 0
			"thread_id", // 1
			"address", // 2
			"person", // 3
			"date", // 4
			"body", // 5
			"read", // 6; 0:not read 1:read; default is 0
			"type", // 7; 0:all 1:inBox 2:sent 3:draft 4:outBox 5:failed
					// 6:queued
			"service_center" // 8
	};
	public static String[] THREAD_COLUMNS = new String[] { "thread_id",
			"msg_count", "snippet" };

	private Context mContext;

	public String getContentUris() {
		String rtn = "{";
		rtn += "\"sms\":\"" + CONTENT_URI_SMS + "\"";
		rtn += ",\"inbox\":\"" + CONTENT_URI_SMS_INBOX + "\"";
		rtn += ",\"sent\":\"" + CONTENT_URI_SMS_SENT + "\"";
		rtn += ",\"conversations\":\"" + CONTENT_URI_SMS_CONVERSATIONS + "\"";
		rtn += "}";
		return rtn;
	}

	public String get(int number) {
		return getData(null, number);
	}

	public String getUnread(int number) {
		return getData("type=1 AND read=0", number);
	}

	public String getRead(int number) {
		return getData("type=1 AND read=1", number);
	}

	public String getInbox(int number) {
		return getData("type=1", number);
	}

	public String getSent(int number) {
		return getData("type=2", number);
	}

	public String getByThread(int thread) {
		return getData("thread_id=" + thread, 0);
	}

	public String getData(String selection, int number) {
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		try {
			if (number > 0) {
				cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
						SMS_COLUMNS, selection, null, "date desc limit "
								+ number);
			} else {
				cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
						SMS_COLUMNS, selection, null, "date desc");
			}
			if (cursor == null || cursor.getCount() == 0)
				return "[]";
			String rtn = "";
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				if (i > 0)
					rtn += ",";
				rtn += "{";
				rtn += "\"_id\":" + cursor.getString(0);
				rtn += ",\"thread_id\":" + cursor.getString(1);
				rtn += ",\"address\":\"" + cursor.getString(2) + "\"";
				rtn += ",\"person\":\""
						+ ((cursor.getString(3) == null) ? "" : cursor
								.getString(3)) + "\"";
				rtn += ",\"date\":" + cursor.getString(4);
				rtn += ",\"body\":\"" + cursor.getString(5) + "\"";
				rtn += ",\"read\":"
						+ ((cursor.getInt(6) == 1) ? "true" : "false");
				rtn += ",\"type\":" + cursor.getString(7);
				rtn += ",\"service_center\":" + cursor.getString(8);
				rtn += "}";
			}
			return "[" + rtn + "]";
		} catch (Exception e) {
			return "[]";
		}
	}

	public List<SMS> getThreads(int number) {
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		List<SMS> list = new ArrayList<SMS>();
		try {
			if (number > 0) {
				cursor = contentResolver.query(
						Uri.parse(CONTENT_URI_SMS_CONVERSATIONS),
						THREAD_COLUMNS, null, null, "thread_id desc limit "
								+ number);
			} else {
				cursor = contentResolver.query(
						Uri.parse(CONTENT_URI_SMS_CONVERSATIONS),
						THREAD_COLUMNS, null, null, "date desc");
			}
			if (cursor == null || cursor.getCount() == 0)
				return list;
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				SMS mmt = new SMS(cursor.getString(0), cursor.getString(1),
						cursor.getString(2), null, null, null, null, null);
				list.add(mmt);
			}
			return list;
		} catch (Exception e) {
			return list;
		}
	}

	public List<SMS> getThreadsNum(List<SMS> ll) {
		Bitmap bitmap = null;
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		List<SMS> list = new ArrayList<SMS>();

		for (SMS mmt : ll) {
			cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
					SMS_COLUMNS, "thread_id = " + mmt.getThread_id(), null,
					null);
			if (cursor == null || cursor.getCount() == 0)
				return list;
			cursor.moveToFirst();
			String name = getContactNameByPhoneNumber(mContext,
					cursor.getString(2));
			if (name == null) {
				mmt.setName(cursor.getString(2));
			} else {
				mmt.setName(name);
			}
			mmt.setAddress(cursor.getString(2));
			bitmap = getIcon(mContext, cursor.getString(2));
			if (bitmap == null) {
				mmt.setIcon(BitmapFactory.decodeResource(mContext.getResources(),R.drawable.ic_launcher));
			} else {
				mmt.setIcon(bitmap);
			}
			mmt.setDate(cursor.getLong(4));
			mmt.setRead(cursor.getString(6));
			list.add(mmt);
		}

		return list;
	}

	/*
	 * 根据电话号码取得联系人姓名
	 */
	public String getContactNameByPhoneNumber(Context context,
			String address) {
		String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER };

		// 将自己添加到 msPeers 中
		Cursor cursor = context.getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				projection, // Which columns to return.
				ContactsContract.CommonDataKinds.Phone.NUMBER + " = '"
						+ address + "'", // WHERE clause.
				null, // WHERE clause value substitution
				null); // Sort order.
		if (cursor == null) {
			System.out.println("null");
			return null;
		}
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			// 取得联系人名字
			int nameFieldColumnIndex = cursor
					.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
			String name = cursor.getString(nameFieldColumnIndex);
			return name;
		}
		return null;
	}
	
	//根据号码查询头像
	public Bitmap getIcon(Context context, String address) {
		Bitmap bitmap = null;
		// 通话电话号码获取头像uri
		Uri uriNumber2Contacts = Uri.parse("content://com.android.contacts/"
				+ "data/phones/filter/" + address);
		Cursor cursorCantacts = context.getContentResolver().query(
				uriNumber2Contacts, null, null, null, null);
		if (cursorCantacts.getCount() > 0) { // 若游标不为0则说明有头像,游标指向第一条记录
			cursorCantacts.moveToFirst();
			Long contactID = cursorCantacts.getLong(cursorCantacts
					.getColumnIndex("contact_id"));
			Uri uri = ContentUris.withAppendedId(
					ContactsContract.Contacts.CONTENT_URI, contactID);
			InputStream input = ContactsContract.Contacts
					.openContactPhotoInputStream(context.getContentResolver(),
							uri);
			bitmap = BitmapFactory.decodeStream(input);
			return bitmap;

		} else {// 么有头像设置默认头像
			return bitmap;

		}
	}
}
